package com.czkj.hwz.decorate.Activity;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czkj.hwz.decorate.MyApp;
import com.czkj.hwz.decorate.R;
import com.czkj.hwz.decorate.adapter.WorkerItemAdapter;
import com.czkj.hwz.decorate.base.HttpUrl;
import com.czkj.hwz.decorate.bean.Worker;
import com.czkj.hwz.decorate.bean.WorkerType;
import com.czkj.hwz.decorate.bean1.ExamineEnterprise;
import com.czkj.hwz.decorate.bean1.User;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.king.base.BaseActivity;
import com.king.base.util.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.okhttpfinal.HttpCycleContext;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.JsonHttpRequestCallback;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Headers;

public class WorkerSearchActivity extends BaseActivity implements HttpCycleContext {
    private static final String TAG = "WorkerSearchActivity";
    protected final String HTTP_TASK_KEY = "HttpTaskKey_" + hashCode();
    private EditText search_text;
    private Spinner spinner_worker;
    private ImageView search;
    private ArrayList<WorkerType> workerTypeLists;
    private int workTypeId;
    private List<Worker> workerList;
    private List<ExamineEnterprise> examineEnterpriseList;
    private List<User> userList;
    private WorkerItemAdapter workerItemAdapter;
    private ListView lv;

    private Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    workerItemAdapter.notifyDataSetChanged();
                    dismissProgressDialog();
                    break;
            }
        }
    };
    @Override
    public void initUI() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.yellow));
        }
        setContentView(R.layout.activity_worker_search);
        getSupportActionBar().hide();
        workerTypeLists=new ArrayList<>();
//        workerTypeLists = (ArrayList<WorkerType>) getIntent().getSerializableExtra("workerTypeLists");
        if (workerTypeLists==null|workerTypeLists.size()==0) {
            MyApp myApp= (MyApp) getApplication();
            workerTypeLists= (ArrayList<WorkerType>) myApp.getWorkerTypeLists();
        }
        Log.d(TAG, "initUI: " + workerTypeLists.toString());
        search_text = findView(R.id.search_text);
        String keyword=getIntent().getStringExtra("keyword");
        search_text.setText(keyword);
        spinner_worker = findView(R.id.spinner_worker);
        search = findView(R.id.search);
        lv = findView(R.id.lv);
        workerList = new ArrayList<Worker>();
        examineEnterpriseList=new ArrayList<ExamineEnterprise>();
        userList=new ArrayList<User>();
        workerItemAdapter = new WorkerItemAdapter(context, workerList,examineEnterpriseList,userList);
    }

    @Override
    public void initData() {
//        WorkerType workerType=new WorkerType();
//        workerType.setName("全部工种");
//        workerType.setId(-1000);
//        if (workerTypeLists==null||workerTypeLists.size()==0) {
//            workerTypeLists.add(0,workerType);
//        }else {
//
//        }
        ArrayAdapter<WorkerType> adapter=new ArrayAdapter<WorkerType>(this,R.layout.simple_spinner_item,workerTypeLists);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_worker.setAdapter(adapter);
        lv.setAdapter(workerItemAdapter);
    }

    @Override
    public void addListeners() {
        search_text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_SEARCH) {
                    if (TextUtils.isEmpty(search_text.getText().toString())) {
                        ToastUtils.showToast(context,"请输入关键字");
                    }else {
                        getData(workTypeId,search_text.getText().toString());
                    }
                }
                return false;
            }
        });
        spinner_worker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                workTypeId=workerTypeLists.get(position).getId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        search_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length()>0) {
                    search.setVisibility(View.VISIBLE);

                }else {
                    search.setVisibility(View.GONE);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(context,WorkerDetailActivity.class);
                intent.putExtra("workerList", (Serializable) workerList);
                intent.putExtra("examineEnterpriseList", (Serializable) examineEnterpriseList);
                intent.putExtra("userList", (Serializable) userList);
                intent.putExtra("position",position);
                startActivity(intent);
            }
        });
    }
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.search:
                getData(workTypeId,search_text.getText().toString());
                break;
        }

    }
    private void getData(int workertypeid,String keyword) {
        showProgressDialog();
        RequestParams params=new RequestParams(this);
        params.addFormDataPart("workertypeid",workertypeid);
        params.addFormDataPart("cmdtype","search");
        params.addFormDataPart("keyword",keyword);
        HttpRequest.get(HttpUrl.WORKER_DATAGRID,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseWorkerData(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });
    }
    private void parseWorkerData(JSONObject jsonObject) {
        try {
            workerList.clear();
            examineEnterpriseList.clear();
            userList.clear();
            JSONArray jsonArray=jsonObject.getJSONArray("rows");
            for (int i=0;i<jsonArray.size();i++) {
                JSONObject jsonObject1=jsonArray.getJSONObject(i);
                Gson gson=new Gson();
                Worker worker=gson.fromJson(jsonObject1.toJSONString(),Worker.class);
                JSONObject jsonObject2 = jsonObject1.getJSONObject("ExamineEnterprise");
                JSONObject jsonObject3 = jsonObject1.getJSONObject("User");
                ExamineEnterprise examineEnterprise=gson.fromJson(jsonObject2.toJSONString(),ExamineEnterprise.class);
                User user=gson.fromJson(jsonObject3.toJSONString(),User.class);
                Log.d(TAG, "parseWorkerData: "+worker.toString());
                Log.d(TAG, "parseWorkerData: "+jsonObject2.toString());
                Log.d(TAG, "parseWorkerData: "+jsonObject3.toString());
                workerList.add(worker);
                examineEnterpriseList.add(examineEnterprise);
                userList.add(user);
            }
            handler.sendEmptyMessage(0);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }
    @Override
    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }
}
